/*
 * Copyright 2010-2011 CGT&DC ISA RAS
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package websolve.workflow.runtime.test.mapreduce;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import websolve.workflow.runtime.Task;
import websolve.workflow.runtime.TaskState;

public class SplitTask extends Task {

    private int partsNum;

    public SplitTask(String name, int partsNum) {
        super(name);
        addInput("in");
        this.partsNum = partsNum;
        for (int i = 0; i < partsNum; i++) {
            addOutput("part" + i);
        }
    }

    @Override
    public void run() {
        setState(TaskState.RUNNING);

        Map input = (Map) getInputValue("in");
        List<Map> outputs = new ArrayList<Map>();
        for (int i = 0; i < partsNum; i++) {
            outputs.add(i, new HashMap());
        }

        int num = 0;
        for (Object key : input.keySet()) {
            outputs.get(num % partsNum).put(key, input.get(key));
            num++;
        }

        for (int i = 0; i < partsNum; i++) {
            setOutputValue("part" + i, outputs.get(i));
        }

        setState(TaskState.DONE);
    }

}
